<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Project;
use App\Models\Purchase;
use App\Services\PurchaseService;
use Illuminate\Http\Request;

class PurchaseController extends Controller
{
    protected $PurchaseService;
    public function __construct(PurchaseService $PurchaseService)
    {
        $this->PurchaseService = $PurchaseService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = $request->title;
        $pageSize = $request->pageSize ?: 10;
        $page = $request->page ?: 1;
        $page = $page * $pageSize - $pageSize;

        $sql = $this->PurchaseService->get($title);
        $sql->where('company_id',$request->company_id);
        $sql->where('project_id',$request->project_id);
        $total = $sql->count();
        $data = $sql->skip($page)->take($pageSize)->orderBy('created_at','desc')->get();
        foreach ($data as $k => $v) {
            $data[$k]->approval_status = '';
            if($v->approval){
                $data[$k]->approval_status = $v->approval->status_text;
            }
        }
        return response()->json(['code' => 200, 'message' => '操作成功','page'=>$page,'pageSize'=>$pageSize,'total'=>$total,'data'=>$data]);
    }

    public function show(Request $request)
    {
        $data = Purchase::find($request->id);
        if($data->delivery_date){
            $data->delivery_date = strtotime($data->delivery_date) * 1000;
        }

        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Responsef
     */
    public function store(Request $request)
    {
        $POSTONLY = Purchase::POSTONLY;
        $input = $request->only($POSTONLY);
        $input['admin_id'] = 0;
        $project = Project::select('id','company_id')->where('number',$request->project_number)->first();
        if(!$project){
            return response()->json(['code' => 200, 'message' => '请重新扫码']);
        }
        $input['company_id'] = $project->company_id;
        $input['project_id'] = $project->id;
        $data = $this->PurchaseService->insert($input);
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }
}
